<?php

class AprTask extends \C\L\Task
{
    public function itemAction()
    {
        $this->runCheck('apr_item', 60);

        $i = 0;
        while ($i < 18) {
            $aprlist = $this->s_itemaprlist->searchPage([
            'status' => 'D',
            'back_time' => time()
            ], ['back_time' => '<='], [], 'id asc', 1, 50);

            foreach ($aprlist as $item) {
                try {
                    $this->db->begin();

                    if (!$this->s_itemaprlist->update($item['id'], ['status' => 'Y', 'ok_time' => time()])) {
                        throw new Exception('更新itemaprlist失败');
                    }

                  // $title = "订单佣金";
                    $title = "订单盈利";
                    if (!$this->s_funds->add($item['uid'], $item['apr_money'], 'money', 'item_apr_money', $title, $item['id'])) {
                        throw new Exception('添加funds失败');
                    }

                    if ($item['money'] > 0) {
                        $title = "订单本金";
                        if (!$this->s_funds->add($item['uid'], $item['money'], 'money', 'item_back_money', $title, $item['id'])) {
                            throw new Exception('添加funds失败');
                        }
                    }

                    $this->db->commit();

                    $this->logs(['msg' => '成功', 'id' => $item['id']]);
                } catch (Exception $e) {
                    if ($this->db->isUnderTransaction()) {
                        $this->db->rollback();
                    }

                    $this->logs(['msg' => $e->getMessage(), 'id' => $item['id']]);
                }
            }

            $i++;
            sleep(3);
        }

        return true;
    }
}
